﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using StockLib.Data;
using System.Windows.Forms;
using System.Runtime.Remoting.Messaging;

namespace StockLib
{
    public delegate void StockContainerDataEventHandler(object sender, EventArgs e);

    public class StockContainer : SortedList<string, Stock>
    {
        public Stock CurrentStock { get; set; }

        /// <summary>
        /// 容器数据更改事件
        /// </summary>
        public event StockContainerDataEventHandler DataChanged;

        /// <summary>
        /// 单例实例
        /// </summary>
        private static StockContainer _instance = new StockContainer();

        /// <summary>
        /// 构造函数
        /// </summary>
        private StockContainer()
            : base()
        {
        }

        /// <summary>
        /// 访问单例
        /// </summary>
        /// <returns></returns>
        public static StockContainer Instance
        {
            get
            {
                return _instance;
            }
        }

        public void Load()
        {
            // 载入代码表
            StockData.Instance.LoadCodeData();
        }

        public void Save()
        {
            // 保存代码表
            StockData.Instance.SaveCodeData();
        }

        /// <summary>
        /// 收到行情数据时，更新容器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void UpdateByReportData(SortedList<string, ReportData> reportData)
        {
            foreach (ReportData report in reportData.Values)
            {
                try
                {
                    Stock stock = null;
                    if (StockContainer.Instance.ContainsKey(report.CodeKey))
                    {
                        stock = StockContainer.Instance[report.CodeKey];
                        stock.Name = report.Name;
                        stock.Report = report;
                    }
                    else
                    {
                        stock = new Stock();
                        stock.Market = report.Market;
                        stock.Code = report.Code;
                        stock.Name = report.Name;
                        stock.Report = report;
                        stock.Type = StockHelper.GetStockType(stock);
                        StockContainer.Instance.Add(stock.CodeKey, stock);
                    }
                }
                catch (Exception ex)
                {
                    Trace.WriteLine(report.Name + report.Code + ex);
                    throw ex;
                }
            }

            RaiseDataChanged(this, EventArgs.Empty);
        }

        public void RaiseDataChanged(object sender, EventArgs e)
        {
            if (DataChanged != null)
            {
                DataChanged(sender, e);
            }
        }
    }
}
